package handlers

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	"strconv"
	"time"
	"travel/cache"
	"travel/models"
	"travel/pkg"
)

func Login(c *gin.Context) {
	username := c.PostForm("username")
	password := c.PostForm("password")
	if username == "" || password == "" {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "字段为空",
		})
		return
	}
	redis_login_key := "login_err" + username
	errCount, _ := cache.Rdb.Get(cache.Ctx, redis_login_key).Int()
	if errCount >= 3 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误三次，禁止登陆",
		})
		return
	}
	var user models.User
	err := models.DB.Where("username = ?", username).First(&user).Error
	if err != nil {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "查询失败",
		})
		return
	}
	if user.ID == 0 {
		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "用户不存在",
		})
		return
	}
	//判断密码是否正确
	if user.Password != pkg.MD5(password) {
		cache.Rdb.Incr(cache.Ctx, redis_login_key)
		if errCount == 2 {
			cache.Rdb.Set(cache.Ctx, redis_login_key, 3, time.Hour*2)
			c.JSON(200, gin.H{
				"code": 500,
				"msg":  "密码错误三次，封禁2个小时",
			})
			return
		}

		c.JSON(200, gin.H{
			"code": 500,
			"msg":  "密码错误",
		})
		return
	}

	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "success",
	})
	return
}
func List(c *gin.Context) {
	page, _ := strconv.Atoi(c.Query("page"))
	size, _ := strconv.Atoi(c.Query("size"))
	offset := (page - 1) * size

	var users []models.User
	redis_list_key := "list_page" + c.Query("page")
	result, _ := cache.Rdb.Get(cache.Ctx, redis_list_key).Result()
	if result == "" {
		models.DB.Offset(offset).Limit(size).Debug().Find(&users)
		jsonData, _ := json.Marshal(users)
		cache.Rdb.Set(cache.Ctx, redis_list_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(result), &users)
	}
	var total int64
	models.DB.Model(&models.User{}).Count(&total)
	c.JSON(200, gin.H{
		"code":  200,
		"msg":   "success",
		"data":  users,
		"total": total,
	})
	return
}
func Detail(c *gin.Context) {
	id := c.Query("id")
	//redis_list_detail_key := "detail_" + id
	//cache.Rdb.Del(cache.Ctx, redis_list_detail_key)
	//c.JSON(200, gin.H{
	//	"code": 200,
	//	"msg":  "success",
	//	//"data": user,
	//})
	//return

	var user models.User
	redis_list_detail_key := "detail_" + id
	result, _ := cache.Rdb.Get(cache.Ctx, redis_list_detail_key).Result()
	if result == "" {
		models.DB.Where("id = ?", id).First(&user).Debug()
		jsonData, _ := json.Marshal(user)
		cache.Rdb.Set(cache.Ctx, redis_list_detail_key, jsonData, time.Hour*2)
	} else {
		json.Unmarshal([]byte(result), &user)
	}
	//err:=models.DB.Where("id = ?",id).First(&user).Error
	//if err!=nil{
	//	c.JSON(200,gin.H{
	//		"code":500,
	//		"msg":"查询失败",
	//		"data":user,
	//	})
	//	return
	//}
	c.JSON(200, gin.H{
		"code": 200,
		"msg":  "success",
		"data": user,
	})
	return
}
